import React, { Component } from 'react';
import {
	StyleSheet,
	Text,
	View,
	Platform,
	Image,
	TouchableOpacity,
	WebView,
	DeviceEventEmitter,
	Animated,
	PanResponder
} from "react-native";
import request from './request';
import { style } from '../../theme/style';
import { GLOBAL } from '../../config/global';
import { ScrollTabView } from '../../component/ScrollTabView';
import { ImgWidthTextButton } from '../../component/ImgWidthTextButton';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { ListDailogModal } from '../../component/ListDailogModal';
import { Common } from '../../component/common/Common';
import SelectComponent from './_component/SelectComponent';
import { BoxShadow } from 'react-native-shadow';
import ToastUtil from '../../utils/toast';
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';

const scale = GLOBAL.SCALE;
const starEmptyWhite = require('../../imgs/report/collect.png');
const starEmpty = require('../../imgs/report/starYellowEmpty.png');
const starYellew = require('../../imgs/report/starYellow.png');
const filter = require('../../imgs/report/filter-new.png');
const bottomImg = require('../../imgs/report/bottomType.jpg');
let that;
let ifCollect;
let rptName;
let rptId;
const shadowOpt = {
	width: GLOBAL.SCREEN_WIDTH,
	height: 60 * scale,
	color: "#000",//阴影颜色
	border: 6 * scale,//阴影宽度
	radius: 0 * scale,//包裹的子元素圆角多少这里必须是多少
	opacity: 0.1,//透明度
	x: 0,
	y: 0,
}
export class ReportIndexPage extends Component {
	constructor(props) {
		super(props);
		let { rptId, choice } = this.props.navigation.state.params || {};
		this.rptId = rptId;
		this.state = {
			collectStatus: 0,
			webViewUrl: '',
			filterWebViewUrl: '',
			filterData: '',//查询条件
			_isLoad: false,
			rptTypesModal: false,
			rptFilterModal: false,
			left: 0,
			attentionFlag: null,
			choice: choice || {}
		}
		that = this;
	}

	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerRight: (
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginRight: 17 }}>
					<TouchableOpacity style={{ marginRight: 12 * scale }} activeOpacity={1}
						onPress={() => {
							that._collect(rptId);
						}}>
						<Image source={ifCollect ? starYellew : starEmptyWhite} style={{ width: 18 * scale, height: 18 * scale }} />
					</TouchableOpacity>
					<TouchableOpacity activeOpacity={1}
						onPress={() =>
							that.toggleFilterModal(rptId)
						}>
						<Image source={filter} style={{ width: 22 * scale, height: 18 * scale }} />
					</TouchableOpacity>
				</View >
			),
			headerTitle: (
				<View style={styles.TitleBox}>
					<TouchableOpacity activeOpacity={1} style={styles.TitleOut} onPress={() => { that._toggleReportTypes(); }}>
						<Text style={styles.TitleText}>{rptName ? rptName : '报表详情'}</Text>
						<Image style={{ marginLeft: 3 * scale }} source={require('../../imgs/Group.png')} />
					</TouchableOpacity>
				</View>
			),
			// headerTitle: rptName ? rptName : '报表详情',
			headerLeft: navigation.state.params && navigation.state.params.rptId ?
				(<Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />) : null,
			headerTintColor: style.color.white,
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				textAlign: 'center',
			}
		}
	}

	async componentWillMount() {
		await this.getSorage();
		await this.initPage();

		//绑定手势事件
		this._panResponder = PanResponder.create({
			onStartShouldSetPanResponder: () => true,
			onMoveShouldSetPanResponder: () => true,
			onPanResponderGrant: () => {
				this._left = this.state.left
			},
			onPanResponderMove: (evt, gs) => {
				this.setState({
					left: this._left + gs.dx
				})
			},
			onPanResponderRelease: (evt, gs) => {
				console.log('release');
				this.setState({
					left: this._left + gs.dx
				})
			}
		})
	}

	componentWillUnmount() {
		//离开当前场景，清楚数据
		ifCollect = null;
		rptName = null;
		rptId = null;
	}

	//获取业务组织
	async getSorage() {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			choice: this.state.choice.corpId ? this.state.choice : { corpId: userInfo.corpId, corpName: userInfo.corpName }
		})
	}

	//初始化,默认第一种类型的第一个报表详情，因返回数组的第一个类型是收藏，所以实际要查询第二类的第一个报表
	initPage() {
		let filterInfoBoxWidth = new Animated.Value(0 * scale);
		let typesBoxHeight = new Animated.Value(0 * scale);
		let filterInfoOpenWidth = GLOBAL.SCREEN_WIDTH;
		let typesBoxOpenHeight = GLOBAL.SCREEN_HEIGHT;

		this._getReportList();

		this.setState({
			filterInfoBoxWidth,
			filterInfoOpenWidth,
			typesBoxHeight,
			typesBoxOpenHeight
		})
	}

	//初始化获取报表列表
	async _getReportList() {
		let reportsList = await request.getReportList({ corpId: this.state.choice.corpId || '' });
		//数据处理，用于显示底部弹出筛选组件
		reportsList = reportsList && reportsList.map((item, index) => {
			//上拉弹框默认选中第一个报表
			if (index === 1 && item.rptDeployVOList[0]) {
				item.rptDeployVOList[0].selected = true;
			}
			return {
				typeId: item.rptTypeVO.typeId,
				typeName: item.rptTypeVO.typeName,
				children: item.rptDeployVOList,
			}
		})

		await this.getCollectList(reportsList);

		for (let i = 0; i < reportsList.length; i++) {
			if (reportsList[i].children && reportsList[i].children.length) {
				if (this.rptId) {
					for (let j = 0; j < reportsList[i].children.length; j++) {
						if (this.rptId == reportsList[i].children[j].rptId) {
							await this.setHeaderInfo(reportsList[i].children[j].rptId, reportsList[i].children[j].rptName, reportsList[i].children[j].attentionFlag);
							await this._setUrl(reportsList[i].children[j].rptId);
							return;
						}
					}
				} else {
					await this.setHeaderInfo(reportsList[i].children[0].rptId, reportsList[i].children[0].rptName, reportsList[i].children[0].attentionFlag);
					await this._setUrl(reportsList[i].children[0].rptId);
					return;
				}
			}
		}
	}

	//获取收藏报表
	async	getCollectList(reportsList) {
		// const { reportsList } = this.state;
		const collectList = await request.getCollectList({ corpId: this.state.choice.corpId || '' });
		if (collectList) {
			reportsList[0].typeName = '收藏';
			reportsList[0].children = collectList.rows;
			reportsList[0].children.map((item, j) => {
				item.attentionFlag = 1;
			})
		} else {
			reportsList[0].typeName = '收藏';
			reportsList[0].children = [];
		}

		this.setState({
			reportsList
		})
	}

	//刷新params  头部信息
	setHeaderInfo = (id, name, flag) => {
		const navigation = this.props.navigation;
		rptName = name;
		rptId = id;
		ifCollect = flag ? 1 : 0;
		navigation.setParams({ status: rptId, status: rptName, status: ifCollect })  //实时更新头部信息
	}

	async _setUrl(id) {
		const response = await this._getDetail(id);
		response && this.setHeaderInfo(response.rptId, response.rptName, response.attentionFlag);

		let webViewUrl = response.resultUrl + (id == rptId ? this.state.filterData : ''); //选择新的报表，清空筛选条件
		let filterWebViewUrl = response.initUrl + (id == rptId ? this.state.filterData : '');
		this.setState({
			webViewUrl,
			filterWebViewUrl
		});
	}

	async _getDetail(rptId) {
		const detail = await request.getReportDetail({ rptId, corpId: this.state.choice.corpId || '' });
		return detail
	}

	// 选择商品
	_confirmPress = (data) => {
		if (data && data.length > 0) {
			this.setState({
				curRptId: data[0].rptId,
				curRptName: data[0].rptName,
				attentionFlag: data[0].rptItem.attentionFlag,
			}, async () => {
				console.log('data', rptId == data[0].rptId)
				if (rptId == data[0].rptId) return;
				rptId = data[0].rptId;
				rptName = data[0].rptName;
				this.setHeaderInfo(data[0].rptId, data[0].rptName, data[0].rptItem.attentionFlag);
				this._setUrl(data[0].rptId);
			})
		}
		this._toggleReportTypes();
	}

	//商品取消按钮
	_cancelPress = (data) => {
		this._toggleReportTypes();
	}

	//点击收藏、取消收藏
	async _collect(rptId) {
		const { reportsList } = this.state;
		await request.collect({ rptId, corpId: this.state.choice.corpId || '' });
		await this.setHeaderInfo(rptId, rptName, !ifCollect);
		reportsList.map((item, index) => {
			return item.children.map((child, index1) => {
				if (child.rptId === rptId) {
					child.attentionFlag = ifCollect;
				}
			})
		})
		await this.getCollectList(reportsList);
	}

	_toggleReportTypes() {
		let { rptTypesModal, typesBoxOpenHeight, typesBoxHeight } = this.state;

		rptTypesModal = !rptTypesModal;
		Animated.timing(typesBoxHeight, {
			duration: 300,
			toValue: rptTypesModal ? typesBoxOpenHeight : 0,
		}).start();
		this.setState({ rptTypesModal })
	}

	//查询面板打开隐藏
	toggleFilterModal = () => {
		let { filterInfoBoxWidth, filterInfoOpenWidth, rptFilterModal } = this.state;

		rptFilterModal = !rptFilterModal;
		Animated.timing(filterInfoBoxWidth, {
			duration: 300,
			toValue: rptFilterModal ? filterInfoOpenWidth : 0,
		}).start();
		this.setState({ rptFilterModal })
	}

	//获取查询信息
	handleMessage(e) {
		if (e.nativeEvent.data) {
			console.log('filter', e.nativeEvent.data)
			let filterData = e.nativeEvent.data;
			let start = filterData.indexOf('&');
			filterData = start === -1 ? '' : filterData.substr(start);
			this.toggleFilterModal();
			this._setUrl(rptId);
			this.setState({ filterData })
		}
	}


	_loadDetailError(e) {
		return (
			<View style={{ flex: 1 }}>
				<PageStatusIndex status='error' onErrorPress={() => this._setUrl(this.state.curRptId)} />
			</View>
		)
	}
	_loadFilterError(e) {
		return (
			<View style={{ flex: 1 }}>
				<PageStatusIndex status='error' onErrorPress={() => this._setUrl(this.state.curRptId)} />
			</View>
		)
	}

	render() {
		const { webViewUrl, filterWebViewUrl, filterInfoBoxWidth, filterData, typesBoxHeight } = this.state;
		const webview = WebView;
		let ProductSend = [];
		if (rptId) {
			ProductSend.push({ rptId, rptName })
		}
		console.log('webViewUrl', webViewUrl)
		return (
			<View style={[styles.container]}>
				{/**报表类型 */}
				{
					this.state.reportsList && this.state.reportsList.length > 0 ?
						<Animated.View style={[{ position: 'absolute', top: 0, zIndex: 9, backgroundColor: '#fff', width: '100%' }, { height: typesBoxHeight, overflow: 'hidden' }]}>
							<SelectComponent
								cancelPress={this._cancelPress}
								confirmPress={this._confirmPress}
								sendData={this.state.reportsList}
								mainCheckData={ProductSend} />
						</Animated.View>
						: null
				}

				{/**报表主体 */}
				<View style={styles.container}>
					{/* <View
					{...this._panResponder.panHandlers}
						style={[{
							backgroundColor: 'red',
							width: 200,
							height: 200,
							borderWidth: 1,
							borderColor: 'black',
							position: 'absolute',
							left: this.state.left
						}]}></View> */}
					<WebView
						ref={'webview'}
						source={
							{
								uri: webViewUrl,
								headers: {
									'Accept': 'application/json',
									'Content-Type': 'application/json',
									"authToken": GLOBAL.TOKEN
								}
							}
						}
						style={{ width: '100%', height: '100%' }}
						onMessage={(e) => {
							this._handleMessage(e)
						}}
						onLoadEnd={(e) => {
							this.refs.webview.postMessage(GLOBAL.TOKEN);
						}}
						renderError={(e) => this._loadDetailError(e)}
						onError={(e) => this._loadDetailError(e)}
						startInLoadingState={true}
					/>
				</View>

				{/**左侧查询面板 */}

				<Animated.View style={[styles.filterContainer, { width: filterInfoBoxWidth, overflow: 'hidden' }]}>
					<TouchableOpacity style={{ height: '100%', width: '100%' }} onPress={() => this.toggleFilterModal()}></TouchableOpacity>
					<View style={styles.filterWebview}>
						<WebView
							ref={'filterWebview'}
							source={{
								uri: filterWebViewUrl,
								headers: {
									'Accept': 'application/json',
									'Content-Type': 'application/json',
									"authToken": GLOBAL.TOKEN
								}
							}}
							style={{ width: '100%', height: '100%' }}
							onMessage={(e) => {
								this.handleMessage(e)
							}}
							renderError={(e) => this._loadFilterError(e)}
							onError={(e) => this._loadFilterError(e)}
							onLoadEnd={() => {
								this.refs.filterWebview.postMessage(filterData);
							}}
							startInLoadingState={true}
						/>
					</View>
				</Animated.View>

			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1
	},
	toggleImg: {
		flexDirection: 'row',
		justifyContent: 'center',
	},
	imgStyle: {
		position: 'relative',
		width: 72 * scale,
		height: 26 * scale,
	},
	filterContainer: {
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		position: 'absolute',
		right: 0,
		top: 0,

	},
	filterWebview: {
		width: '80%',
		height: (GLOBAL.SCREEN_HEIGHT - (GLOBAL.IS_IPHONEX ? 170 : 110)) * scale,
		position: 'absolute',
		right: 0,
		backgroundColor: '#fff'
	},
	TitleBox: {
		flex: 1
	},
	TitleOut: {
		width: '100%',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	TitleText: { color: '#fff', fontSize: 16 * scale },
})